package com.demo.nio.server;

import com.demo.nio.client.CustomTextFrameHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 *
 * @author
 * @since
 */
public class PopMessageServer {

    public void openServer(int port){
      ServerBootstrap bootStrap = new ServerBootstrap();
      // set channel
      bootStrap.channel(NioServerSocketChannel.class);
      // set group
      EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1) ;
      EventLoopGroup work = new NioEventLoopGroup(8) ;
      bootStrap.group(eventLoopGroup, work);
      //
      bootStrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
          nioSocketChannel.pipeline().addLast("http-response", new HttpResponseEncoder());
          nioSocketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
          nioSocketChannel.pipeline().addLast("http-response-encode", new HttpObjectAggregator(65536));
          nioSocketChannel.pipeline().addLast("web-socket", new WebSocketServerProtocolHandler("/ws"));
          nioSocketChannel.pipeline().addLast("cus-text", new CustomTextFrameHandler());
        }});

      bootStrap.option(ChannelOption.SO_BACKLOG, 128);
      bootStrap
          .childOption(ChannelOption.SO_KEEPALIVE, true)
          .childOption(ChannelOption.TCP_NODELAY, true);

      try {
        ChannelFuture cf = bootStrap.bind(port).sync();
        System.out.println("服务已启动：" + port);
        cf.channel().closeFuture().sync();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        eventLoopGroup.shutdownGracefully();
        work.shutdownGracefully();
      }
    }


  public static void main(String[] args){
    int port;
    if (args.length > 0) {
      port = Integer.parseInt(args[0]);
    } else {
      port = 20001;
    }
    new PopMessageServer().openServer(port);
  }


}


